package com.kkm.dao.Imp;

import com.kkm.dao.AdminDao;
import com.kkm.pojo.Admin;
import com.kkm.pojo.Type;
import com.kkm.util.JdbcUtils_Druid;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class AdminDaoImp implements AdminDao {
    private JdbcTemplate template=new JdbcTemplate(JdbcUtils_Druid.getDataSource());

    @Override
    public Admin login(Admin admin) {
        try {
            String sql = "select * from admin  where password=? and phone=? ";
            System.out.println(admin.getPhone());
            System.out.println(admin.getPassword());
            return template.queryForObject(sql, new BeanPropertyRowMapper<Admin>(Admin.class),
                     admin.getPassword(),admin.getPhone());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("null_error");
            return null;
        }
    }

    @Override
    public Admin checkAdminById(int aid) {
        String sql = "select * from admin  where id=? ";
        return template.queryForObject(sql,new BeanPropertyRowMapper<Admin>(Admin.class),aid);
    }

    @Override
    public void changePass(Map<String, String[]> condition, int aid) {
        String sql="update admin set ";
        //解析map  1.对sql拼接
        StringBuffer sb=new StringBuffer(sql);
        //2.获取键值，name address，email
        Set<String> keySet=condition.keySet();
        //3.定义参数集合
        List<Object> params=new ArrayList<Object>();
        //遍历看那个不为空拼接到sql语句中
        //key：name，address，email
        for(String key:keySet){
            //排除分页条件参数
            if ("currentPage".equals(key)||"rows".equals(key)||"method".equals(key)){
                continue;
            }
            String value=condition.get(key)[0];//获取值
            if(!"".equals(value)){
                if(key.equals("name")){
                    sb.append(" "+key+" = ? ");
                    params.add(value);
                }else if (key.equals("id")){

                }else {
                    //有值
                    sb.append(", "+key+" = ? ");
                    params.add(value);
                }
            }
        }
        sb.append(" where id=? ");
        params.add(aid);
        sql=sb.toString();
        System.out.println("修改的sql："+sql);
        template.update(sql,params.toArray());
    }
}
